// 获取express模块
var express = require('express');
var app = express();

// 获取一个bodyParse的模块
var bodyParse = require('body-parser');
var bodyUrlParse = bodyParse.urlencoded({extended: false});

var deck = [
    {
        name: '工程师学徒'
    },
    {
        name: '铸甲师'
    },
    {
        name: '暴虐食尸鬼'
    }];

// 使用中间件处理JS脚本文件加载的请求
app.use('/scripts', express.static(__dirname));

// 创建一个中间件，负责打印日志
app.use(function (req, res, next) {
    // 获取起始时间
    var start = +new Date();

    // 控制台输出流
    var stream = process.stdout;

    // 监听response的finish事件并打印日志
    res.on('finish', function () {
        var duration = +new Date() - start;
        stream.write('Get ' + req.path + ' took ' + duration + ' ms');
    });

    next();
});

// 监听请求
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/html/ajax_card.html');
});

// 发送JSON数据
app.get('/deck', function (req, res) {
    res.json(deck);
});

// 创建新卡
app.post('/card_add', bodyUrlParse, function (req, res) {
    deck.push(req.body);
    res.status(201).json(req.body);
});

// 删除卡牌
app.delete('/card_delete/:cardname', function (req, res) {
    var card_name = req.params.cardname;
    var del_index = -1;
    for(var i=0;i < deck.length; i++) {
        if(deck[i].name == card_name) {
            del_index = i;
            break;
        }
    }
    if(-1 < del_index) {
        var a1 = deck.splice(0,del_index);
        var a2 = deck.splice(del_index+1);
        deck = a1.concat(a2);
    }
    res.sendStatus(200);
});

// 监听8080
app.listen(8080);